<template>
  <div class="app-container">
    <el-card>
      <!-- 搜索表单 -->
      <el-form :model="queryParams" ref="queryFormRef" :inline="true" class="search-form">
        <el-form-item label="菜单名称" prop="name">
          <el-input v-model="queryParams.name" placeholder="请输入菜单名称" clearable style="width: 240px" @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 240px">
            <el-option v-for="dict in statusOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleQuery">搜索</el-button>
          <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 操作按钮 -->
      <el-row :gutter="10" class="mb-3">
        <el-col :span="1.5">
          <el-button type="primary" :icon="Plus" @click="handleAdd">新增</el-button>
        </el-col>
      </el-row>

      <!-- 表格 -->
      <el-table
        v-loading="loading"
        :data="menuList"
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column prop="name" label="菜单名称" :show-overflow-tooltip="true" />
        <el-table-column prop="icon" label="图标" align="center" width="100">
          <template #default="scope">
            <svg-icon v-if="scope.row.icon" :icon-class="scope.row.icon" />
          </template>
        </el-table-column>
        <el-table-column prop="sort" label="排序" align="center" width="80" />
        <el-table-column prop="path" label="路由地址" :show-overflow-tooltip="true" />
        <el-table-column prop="component" label="组件路径" :show-overflow-tooltip="true" />
        <el-table-column prop="permission" label="权限标识" :show-overflow-tooltip="true" />
        <el-table-column label="类型" align="center" width="80">
          <template #default="scope">
            <el-tag v-if="scope.row.type === 0" type="danger">目录</el-tag>
            <el-tag v-else-if="scope.row.type === 1" type="success">菜单</el-tag>
            <el-tag v-else-if="scope.row.type === 2" type="info">按钮</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" align="center" width="100">
          <template #default="scope">
            <dict-tag dict-type="sys_normal_disable" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" width="160">
          <template #default="scope">
            <span>{{ formatDateTime(scope.row.createdAt) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="180" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button type="primary" link :icon="Plus" @click="handleAdd(scope.row)" v-if="scope.row.type !== 2">新增</el-button>
            <el-button type="primary" link :icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button type="danger" link :icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加或修改菜单对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="600px" append-to-body>
      <el-form ref="menuFormRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="上级菜单">
          <el-tree-select
            v-model="form.parentId"
            :data="menuOptions"
            :props="{ label: 'name', children: 'children', value: 'id' }"
            value-key="id"
            placeholder="请选择上级菜单"
            check-strictly
            clearable
          />
        </el-form-item>
        <el-form-item label="菜单类型" prop="type">
          <el-radio-group v-model="form.type">
            <el-radio :label="0">目录</el-radio>
            <el-radio :label="1">菜单</el-radio>
            <el-radio :label="2">按钮</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="菜单名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入菜单名称" />
        </el-form-item>
        <el-form-item label="图标" prop="icon" v-if="form.type !== 2">
          <el-popover
            placement="bottom-start"
            trigger="click"
            :width="450"
            v-model:visible="iconSelectVisible"
          >
            <template #reference>
              <el-input v-model="form.icon" placeholder="点击选择图标" readonly>
                <template #prefix>
                  <svg-icon v-if="form.icon" :icon-class="form.icon" />
                  <el-icon v-else><Picture /></el-icon>
                </template>
              </el-input>
            </template>
            <icon-select @selected="selected" />
          </el-popover>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" :min="0" :max="999" controls-position="right" />
        </el-form-item>
        <el-form-item label="路由地址" prop="path" v-if="form.type !== 2">
          <el-input v-model="form.path" placeholder="请输入路由地址" />
        </el-form-item>
        <el-form-item label="组件路径" prop="component" v-if="form.type === 1">
          <el-input v-model="form.component" placeholder="请输入组件路径" />
        </el-form-item>
        <el-form-item label="路由参数" prop="query" v-if="form.type === 1">
          <el-input v-model="form.query" placeholder="请输入路由参数" />
        </el-form-item>
        <el-form-item label="是否外链" prop="isExternal" v-if="form.type !== 2">
          <el-radio-group v-model="form.isExternal">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="显示状态" prop="isHidden" v-if="form.type !== 2">
          <el-radio-group v-model="form.isHidden">
            <el-radio :label="0">显示</el-radio>
            <el-radio :label="1">隐藏</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="权限标识" prop="permission" v-if="form.type !== 0">
          <el-input v-model="form.permission" placeholder="请输入权限标识" />
        </el-form-item>
        <el-form-item label="菜单状态" prop="status">
          <dict-radio
            v-model="form.status"
            dict-type="sys_normal_disable"
          />
        </el-form-item>
        <el-form-item label="显示状态" prop="visible" v-if="form.type !== 'F'">
          <dict-radio
            v-model="form.visible"
            dict-type="sys_show_hide"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="dialog.visible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Edit, Delete, Picture } from '@element-plus/icons-vue'
import { 
  getMenuList, 
  getMenuDetail,
  getMenuSelectData, 
  createMenu, 
  updateMenu, 
  deleteMenu, 
  updateMenuStatus 
} from '@/api/menu'
import SvgIcon from '@/components/SvgIcon/index.vue'
import IconSelect from '@/components/IconSelect/index.vue'
import Pagination from '@/components/Pagination/index.vue'
import useDict from '@/hooks/useDict'

// 状态数据字典
const statusOptions = [
  { value: 1, label: '正常' },
  { value: 0, label: '停用' }
]

// 查询参数
const queryParams = reactive({
  name: '',
  status: null
})

// 表格数据
const menuList = ref([])
const menuOptions = ref([])
const loading = ref(false)
const queryFormRef = ref(null)
const menuFormRef = ref(null)
const iconSelectVisible = ref(false)

// 表单参数
const form = reactive({
  id: null,
  parentId: null,
  name: '',
  icon: '',
  path: '',
  component: '',
  query: '',
  sort: 0,
  type: 0,
  permission: '',
  isExternal: 0,
  isHidden: 0,
  status: 1
})

// 表单校验规则
const rules = {
  name: [
    { required: true, message: '菜单名称不能为空', trigger: 'blur' }
  ],
  path: [
    { required: true, message: '路由地址不能为空', trigger: 'blur' }
  ],
  component: [
    { required: true, message: '组件路径不能为空', trigger: 'blur' }
  ]
}

// 菜单表单对话框
const dialog = reactive({
  title: '',
  visible: false
})

// 字典数据
const { dicts } = useDict('sys_normal_disable', 'sys_show_hide')

// 格式化日期时间
const formatDateTime = (value) => {
  if (!value) return ''
  return new Date(value).toLocaleString()
}

// 获取菜单列表
const getList = async () => {
  loading.value = true
  try {
    const res = await getMenuList(queryParams)
    menuList.value = res.data
  } catch (error) {
    console.error('获取菜单列表失败:', error)
    ElMessage.error('获取菜单列表失败')
  } finally {
    loading.value = false
  }
}

// 获取菜单选择数据
const getMenuOptions = async () => {
  try {
    const res = await getMenuSelectData()
    menuOptions.value = res.data
  } catch (error) {
    console.error('获取菜单选择数据失败:', error)
    ElMessage.error('获取菜单选择数据失败')
  }
}

// 搜索按钮操作
const handleQuery = () => {
  getList()
}

// 重置按钮操作
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

// 图标选择事件
const selected = (name) => {
  form.icon = name
  iconSelectVisible.value = false
}

// 表单重置
const resetForm = () => {
  menuFormRef.value?.resetFields()
  Object.assign(form, {
    id: null,
    parentId: null,
    name: '',
    icon: '',
    path: '',
    component: '',
    query: '',
    sort: 0,
    type: 0,
    permission: '',
    isExternal: 0,
    isHidden: 0,
    status: 1
  })
}

// 状态修改
const handleStatusChange = async (row) => {
  try {
    await updateMenuStatus(row.id, row.status)
    ElMessage.success(`修改菜单状态成功`)
  } catch (error) {
    console.error('修改菜单状态失败:', error)
    ElMessage.error('修改菜单状态失败')
    row.status = row.status === 1 ? 0 : 1
  }
}

// 新增按钮操作
const handleAdd = (row) => {
  resetForm()
  dialog.title = '添加菜单'
  dialog.visible = true
  if (row) {
    form.parentId = row.id
  }
}

// 修改按钮操作
const handleUpdate = async (row) => {
  resetForm()
  dialog.title = '修改菜单'
  dialog.visible = true
  
  try {
    const res = await getMenuDetail(row.id)
    Object.assign(form, res.data)
  } catch (error) {
    console.error('获取菜单详情失败:', error)
    ElMessage.error('获取菜单详情失败')
  }
}

// 提交表单
const submitForm = () => {
  menuFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        loading.value = true
        if (form.id) {
          // 修改
          await updateMenu(form.id, form)
          ElMessage.success('修改菜单成功')
        } else {
          // 新增
          await createMenu(form)
          ElMessage.success('新增菜单成功')
        }
        dialog.visible = false
        getList()
      } catch (error) {
        console.error(form.id ? '修改菜单失败:' : '新增菜单失败:', error)
        ElMessage.error(form.id ? '修改菜单失败' : '新增菜单失败')
      } finally {
        loading.value = false
      }
    }
  })
}

// 删除按钮操作
const handleDelete = (row) => {
  ElMessageBox.confirm(`确认删除菜单"${row.name}"吗?`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteMenu(row.id)
      ElMessage.success('删除成功')
      getList()
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  })
}

// 监听菜单类型变化
watch(() => form.type, (val) => {
  if (val === 2) {
    form.component = ''
    form.path = ''
    form.icon = ''
    form.isExternal = 0
    form.isHidden = 0
  }
})

onMounted(() => {
  getList()
  getMenuOptions()
})
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.search-form {
  margin-bottom: 20px;
}

.mb-3 {
  margin-bottom: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style> 